<template>
  <!-- 搜索组件 -->
  <div class="header">
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline"
      @submit="search">
      <el-form-item label="公司名称" prop="search">
        <el-input
          v-model="searchData"
          placeholder="请输入查询公司名称"
          @clear="search"
          clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" :icon="Search" @click="search"
          >查询</el-button
        >
      </el-form-item>
    </el-form>
    <el-button
      class="button"
      color="#626aef"
      :icon="DocumentAdd"
      @click="addBtn"
      >新增</el-button
    >
  </div>
  <!-- table组件 -->
  <el-table
    :data="
      companyData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
    "
    @row-contextmenu="RightMenu"
    @row-click="rowClick"
    @row-dblclick="dblclick"
    header-row-class-name="table-header"
    v-loading="loading"
    element-loading-text="Loading..."
    :element-loading-spinner="svg"
    element-loading-svg-view-box="-10, -10, 50, 50"
    element-loading-background="rgba(162, 162, 162, 0.7)"
    border
    style="width: 100%">
    <el-table-column
      width="50px"
      header-align="center"
      prop="id"
      align="center"
      type="index"
      label="编号"></el-table-column>
    <el-table-column
      prop="companyName"
      header-align="center"
      min-width="200px"
      show-overflow-tooltip
      label="公司名称"></el-table-column>
    <el-table-column
      prop="busRegistNo"
      header-align="center"
      width="200px"
      show-overflow-tooltip
      label="工商注册号"></el-table-column>
    <el-table-column
      prop="address"
      min-width="250px"
      header-align="center"
      show-overflow-tooltip
      label="地址"></el-table-column>
    <el-table-column
      prop="tel"
      header-align="center"
      width="160px"
      label="电话"></el-table-column>
    <el-table-column
      prop="bankName"
      header-align="center"
      min-width="220px"
      show-overflow-tooltip
      label="开户银行"></el-table-column>
    <el-table-column
      prop="account"
      header-align="center"
      width="160px"
      show-overflow-tooltip
      label="开户账号"></el-table-column>
    <el-table-column
      label="是否启用"
      header-align="center"
      align="center"
      width="100px">
      <template #default="{ row }">
        <el-switch
          disabled
          v-model="row.status"
          :active-value="1"
          :inactive-value="0"></el-switch>
      </template>
    </el-table-column>
    <el-table-column
      label="操作"
      header-align="center"
      width="180px"
      align="center">
      <template #default="scope">
        <el-row style="margin-left: 15px">
          <el-tooltip content="显示更多" placement="bottom" effect="light">
            <el-button
              :icon="More"
              type="success"
              circle
              @click="viewBtn(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="编辑修改" placement="bottom" effect="light">
            <el-button
              :icon="Edit"
              type="primary"
              circle
              @click="openDialogBtn(scope.row)"></el-button>
          </el-tooltip>
          <el-popconfirm title="确定要删除吗？" @confirm="delBtn(scope.row)">
            <template #reference>
              <el-button :icon="Delete" type="danger" circle></el-button>
            </template>
          </el-popconfirm>
        </el-row>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页组件 -->
  <div class="pagination">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10]"
      :background="false"
      :disabled="disabled"
      layout=" prev, pager, next, jumper,->,total, sizes,"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
  <!-- 子组件-修改及新增 -->
  <Operate ref="operateRef"></Operate>
</template>

<script setup lang="ts" name="Company">
  import {
    ref,
    DefineComponent,
    reactive,
    toRefs,
    computed,
    onMounted,
    onBeforeMount,
    watch,
  } from "vue";
  import {
    Search,
    DocumentAdd,
    Delete,
    Edit,
    More,
  } from "@element-plus/icons-vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { $contextmenu } from "vue-contextmenu-next/index";
  // import { useRouter } from "vue-router";
  import { storeToRefs } from "pinia";
  import Operate from "./components/operate.vue";
  import useCompanyStore from "@/store/modules/company";
  import { ICompanyInfo } from "@/apis/company/type";
  import { ICompanyParas } from "@/apis/company/type";

  const svg = `
            <path class="path" d="
              M 30 15
              L 28 17
              M 25.61 25.61
              A 15 15, 0, 0, 1, 15 30
              A 15 15, 0, 1, 1, 27.99 7.5
              L 15 15
            " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>`;
  //#region 响应式ref

  // 操作组件
  // const router = useRouter();
  const operateRef = ref<DefineComponent>();

  const companyStore = useCompanyStore();

  // 从小仓库中提取属性同时保持其响应式
  const { companyInfo } = storeToRefs(companyStore);

  const formInline = reactive<{ searchData: string }>({
    searchData: "",
  });
  const { searchData } = toRefs(formInline);
  const state = reactive<{
    currentPage: number;
    pageSize: number;
    disabled: boolean;
    companyData: ICompanyInfo[];
    loading: boolean;
  }>({
    currentPage: 1,
    pageSize: 10,
    disabled: false,
    companyData: [],
    loading: false,
  });

  const { currentPage, pageSize, disabled, companyData, loading } =
    toRefs(state);
  //#endregion

  //#region 分页设置逻辑
  const total = computed(() => companyData.value.length);
  const handleSizeChange = (val: number) => {
    pageSize.value = val;
    currentPage.value = 1;
  };

  const handleCurrentChange = (val: number) => {
    currentPage.value = val;
  };
  //#endregion

  //#region 生命周期钩子函数
  // 组件挂载前
  onBeforeMount(() => {
    loading.value = true;
  });
  //组件挂载后
  onMounted(() => {
    loadData();
  });
  //#endregion

  //#region 方法定义

  //监测数据变化
  watch(companyInfo, () => {
    search();
    loading.value = false;
  });

  // 加载数据;
  // 1、组件加载时执行一次；
  // 2、 将方法传入到子组件中, 更新与新建组件可以执行此方法；
  const loadData = () => {
    companyStore.getInfo();
  };

  const search = () => {
    // e!.preventDefault();
    if (!searchData.value) {
      //权限控制使用
      companyData.value = companyStore.companyInfo.filter(
        item => item.status === 1
      );
      // companyData.value = companyStore.companyInfo;
    } else {
      companyData.value = companyStore.companyInfo.filter(item =>
        item.companyName?.includes(searchData.value)
      );
    }
  };
  //#endregion

  //#region 操作按钮函数

  //打开子组件
  const openDialogBtn = (row: ICompanyInfo) => {
    const param: ICompanyParas = {
      row,
      type: "edit",
    };
    operateRef.value?.open(param);
  };

  const viewBtn = (row: ICompanyInfo) => {
    const param: ICompanyParas = {
      row,
      type: "view",
    };
    operateRef.value?.open(param);
  };

  const addBtn = () => {
    const param: ICompanyParas = {
      type: "add",
    };
    operateRef.value?.open(param);
  };

  const delBtn = (row: ICompanyInfo) => {
    if (row.status === 1) {
      const data = { ...row, status: 0 };
      companyStore.updateCompany(data._id!, data);
    } else {
      companyStore.deleteCompany(row._id as string);
    }
    loadData();
  };

  /**
   * 判断是否包含标题；
   * 方便鼠标位置在有效的地方操作；
   * @param title 标题
   */
  const isHasTitle = (title: string) => {
    const nameArr = [
      "编号",
      "公司名称",
      "工商注册号",
      "地址",
      "电话",
      "开户银行",
      "开户账号",
    ];
    return nameArr.includes(title);
  };

  // table 右键逻辑
  const RightMenu = (row: ICompanyInfo, col: any, e: MouseEvent) => {
    e.preventDefault();
    if (!isHasTitle(col.label)) return;
    $contextmenu({
      x: e.clientX,
      y: e.clientY,
      width: "120px",
      itemHeight: "30px",
      bgColor: "#eee",
      menuList: [
        {
          text: "刷新",
          icon: "Refresh",
          onClick: () => {
            companyStore.getInfo();
            rowClick();
          },
        },
        {
          text: "新增",
          icon: "DocumentAdd",
          onClick: () => {
            addBtn();
            rowClick();
          },
        },
        {
          text: "更新",
          icon: "Edit",
          onClick: () => {
            openDialogBtn(row);
            rowClick();
          },
        },
        {
          text: "删除",
          icon: "Delete",
          onClick: () => {
            ElMessageBox.confirm("确定要删除吗?", "删除提示", {
              confirmButtonText: "确定",
              cancelButtonText: "放弃",
              type: "warning",
            })
              .then(() => {
                delBtn(row);
                ElMessage.success("删除成功");
                //整体刷新
                // router.go(0);
                companyStore.getInfo();
              })
              .catch(() => {
                ElMessage.info("删除已取消");
              })
              .finally(() => {
                rowClick();
              });
          },
        },
      ],
    });
    window.setTimeout(() => {
      $contextmenu.destroy();
    }, 10000);
  };

  //当某一行被点击时会触发该事件；
  //取消右键菜单
  const rowClick = () => {
    $contextmenu.destroy();
  };

  const dblclick = (row: ICompanyInfo, col: any, e: MouseEvent) => {
    e.preventDefault();
    if (!isHasTitle(col.label)) return;
    viewBtn(row);
  };

  //#endregion
</script>

<style scoped lang="scss">
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .el-input {
      --el-input-width: 220px;
    }
  }
  :deep(.table-header) {
    font-size: 16px;
    font-weight: 400;
    color: #555;
  }

  .pagination {
    margin-top: 20px;
    background: linear-gradient(90deg, #d5dee6, #558dd6, #d5dee6);
    padding: 10px 5px;
  }
  .menuDiv {
    display: flex;
    position: absolute;

    z-index: 1000;
    .menuUl {
      display: block;
      height: auto;
      width: 120px;
      font-size: 14px;
      text-align: left;
      border-radius: 5px;
      border: none;
      background-color: #fff;
      color: #555;
      list-style: none;
      padding: 10px 15px;
      box-sizing: border-box;
      box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.2);
      li {
        width: 140px;
        height: 35px;
        line-height: 35px;
        cursor: pointer;
        border-bottom: 1px solid rgba(255, 255, 255, 0.47);
        span {
          padding-left: 10px;
        }
        &:hover {
          color: rgb(54, 138, 175);
        }
      }
    }
  }
</style>
